package com.taro.blog.dao;

import com.taro.blog.model.User;
import com.taro.blog.util.DBUtil;
import lombok.SneakyThrows;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UserDao {

    @SneakyThrows
    public User registerByUsernameAndPassword(String username , String password , String git_repo){
        String sql = "insert into users (username, password , avatar , git_repo) values (?, ?, ?, ?)";
        User user = new User();
        try (Connection c = DBUtil.connection()){
            try (PreparedStatement ps = c.prepareStatement(sql)){
                String avatar = "https://www.keaidian.com/uploads/allimg/190410/10173740_7.jpg";
                ps.setString(1 , username);
                ps.setString(2 , password);
                ps.setString(3 , avatar);
                ps.setString(4 , git_repo);
                ps.executeUpdate();
                user = selectOneByUsernameAndPassword(username , password);


            }
        }
        return user;

    }
    @SneakyThrows
    public User selectOneByUsernameAndPassword(String username, String password) {
        String sql = "select uid, avatar, git_repo from users where username = ? and password = ?";
        try (Connection c = DBUtil.connection()) {
            try (PreparedStatement ps = c.prepareStatement(sql)) {
                ps.setString(1, username);
                ps.setString(2, password);

                System.out.println("DEBUG: " + ps);
                try (ResultSet rs = ps.executeQuery()) {
                    if (!rs.next()) {
                        return null;
                    }

                    User user = new User();
                    user.uid = rs.getInt("uid");
                    user.username = username;
                    user.password = password;
                    user.avatar = rs.getString("avatar");
                    user.gitRepo = rs.getString("git_repo");

                    return user;
                }
            }
        }
    }
}
